import { createHashRouter, type RouteObject } from "react-router";
import React, { createElement } from "react";

// 动态加载路由文件
// 匹配所有 .router.tsx 或 .router.jsx 文件
const pages = import.meta.glob("/src/pages/**/*.{router.tsx,router.jsx}", {
  eager: true,
});

// 动态加载 meta 文件
// 匹配所有 .meta.ts 或 .meta.js 文件
const metas = import.meta.glob("/src/pages/**/*.meta.{ts,js}", { eager: true });

// 动态加载布局组件
const layoutModules = import.meta.glob("/src/layout/*.tsx", { eager: true });
const layouts = Object.fromEntries(
  Object.entries(layoutModules).map(([path, module]) => {
    const name = path.match(/\/layout\/(.*)\.tsx$/)?.[1];
    return [name || "DefaultLayout", module.default];
  })
);
console.log(pages);

interface Meta {
  layout?: string;
  [key: string]: any;
}

interface RouteMap {
  [key: string]: {
    path: string;
    element?: React.ReactNode;
    children: RouteMap;
    meta?: Meta;
  };
}

const generateRoutes = (basePath = "/src/pages"): RouteObject[] => {
  const routeMap: RouteMap = {};

  Object.entries(pages).forEach(([path, element]) => {
    const relativePath = path
      .replace(basePath, "")
      .replace(/\/index\.router\.(tsx|jsx)$/, "")
      .toLocaleLowerCase();

    const fullPath = relativePath === "" ? "/" : relativePath.slice(1);
    const routeParts = fullPath.split("/");
    console.log(relativePath, "relativePath");
    console.log(fullPath, "fullPath");
    console.log(routeParts, "routeParts");

    const metaTsName = path.replace(/\.router\.(tsx|jsx)$/, ".meta.ts");
    const metaJsName = path.replace(/\.router\.(tsx|jsx)$/, ".meta.js");
    const meta = (metas[metaTsName]?.default ||
      metas[metaJsName]?.default ||
      {}) as Meta;
    const layoutName = meta.layout ?? "DefaultLayout";

    let currentLevel = routeMap;
    let accumulatedPath = "";
    routeParts.forEach((part, index) => {
      accumulatedPath += `/${part}`;

      if (!currentLevel[part]) {
        currentLevel[part] = {
          path: accumulatedPath,
          children: {},
        };
      }

      if (index === routeParts.length - 1) {
        const layoutComponent = layouts[layoutName];
        currentLevel[part].element = layoutComponent
          ? createElement(layoutComponent, {}, element as React.ReactNode)
          : (element as React.ReactNode);
        currentLevel[part].meta = meta;
      }

      currentLevel = currentLevel[part].children;
    });
  });

  const convertToRoutesArray = (routeObj: RouteMap): RouteObject[] => {
    return Object.entries(routeObj).map(([, route]) => ({
      path: route.path,
      element: route.element,
      children:
        Object.keys(route.children).length > 0
          ? convertToRoutesArray(route.children)
          : undefined,
      meta: route.meta,
    }));
  };

  return convertToRoutesArray(routeMap);
};

const routes = generateRoutes();
console.log(routes);

// // 官方路由的模式
// const routes_back: RouteObject[] = [
//   {
//     path: "/",
//     element: <App />,
//     handle: {
//       name: "",
//       layout: false,
//     },
//     children: [
//       {
//         index: true,
//         path: "/home",
//         element: <Home />,
//         handle: {
//           name: "主页",
//         },
//       },
//     ],
//   },
// ];

export const router = createHashRouter(routes);
